#!/bin/bash
# usage: testpythonio filename timeout judgetype
#
# test configuration variables:
#
PYTHON_PATH="/list_test_files"
OUTPUT_FILE="$PYTHON_PATH/__list_output.txt"
PYTHON_ARGS=""
PROGRAM_OUTPUT_FILE="$PYTHON_PATH/program.out"
FILENAME=$1
TIMEOUT=$2
RUNFILE="$PYTHON_PATH/$FILENAME.py"
TEST_INPUT="$PYTHON_PATH/test_data/test_input.txt"
TEST_TARGET="$PYTHON_PATH/test_data/test_target.txt"
TEST_JUDGE_SCRIPT="$PYTHON_PATH/test_data/test_judge.py"
#
#
#
echo "<pre>" > $OUTPUT_FILE
#
echo "Stage 1 / 1: running test ..." >> $OUTPUT_FILE
echo "----- Running user code from file $FILENAME.py<br />" >> ../$OUTPUT_FILE
#sudo -u testovac /var/www/list-svn/svn/dev/test_scripts/development/testpythonio2 $1 > ../$PROGRAM_OUTPUT_FILE 2>> ../$OUTPUT_FILE
cat $TEST_INPUT | nice run_with_timeout $TIMEOUT /usr/bin/python3.4 $PYTHON_ARGS $RUNFILE > $PROGRAM_OUTPUT_FILE 2>> $OUTPUT_FILE
STATUS=$?
#
if [[ $STATUS == 0 ]] ; then
	if [[ "$3" == "judge-type-diff" ]] ; then
		diff $TEST_TARGET $PROGRAM_OUTPUT_FILE > /dev/null 2> /dev/null
		JUDGE_STATUS=$?
		if [[ $JUDGE_STATUS == 0 ]] ; then
			echo "----- Result matches expected target!" >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 0
		else
			echo "----- Result is else that expected target!" >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 1
		fi
	fi
	if [[ "$3" == "judge-type-script" ]] ; then
		cat $PROGRAM_OUTPUT_FILE | nice run_with_timeout 300000 /usr/bin/python3.4 $TEST_JUDGE_SCRIPT $TEST_INPUT >> $OUTPUT_FILE 2>> $OUTPUT_FILE
		JUDGE_STATUS=$?
		cd .. ;
		if [[ $JUDGE_STATUS == 0 ]] ; then
			echo "----- Result pass judge script successfully." >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 0
		else
			echo "----- Result failed to pass judge script." >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 1
		fi
	fi
	echo "----- NO JUDGE SPECIFIED!" >> $OUTPUT_FILE
	echo "</pre>" >> $OUTPUT_FILE
	exit 10
else
	echo "----- RUN TIME ERROR!" >> $OUTPUT_FILE
	echo "</pre>" >> $OUTPUT_FILE
	exit 100
fi
